package com.evan.review.ipc;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Process;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.ArrayList;

/**
 * Messenger服务
 * 使用Messenger实现跨进程通信的服务端
 */
public class MessengerService extends Service {
    private static final String TAG = "MessengerService";

    // 保存所有已连接的客户端Messenger
    private final ArrayList<Messenger> clients = new ArrayList<>();

    // 当前消息内容
    private String currentValue = "默认消息";

    // 处理客户端发送的消息
    private class IncomingHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int pid = Process.myPid();
            Log.d(TAG, "处理消息: " + msg.what + "，来自客户端，服务进程PID: " + pid);

            switch (msg.what) {
                case MessengerDemoActivity.MSG_REGISTER_CLIENT:
                    // 注册客户端
                    if (msg.replyTo != null && !clients.contains(msg.replyTo)) {
                        clients.add(msg.replyTo);
                        Log.d(TAG, "客户端已注册，当前客户端数量: " + clients.size());
                    }
                    break;
                case MessengerDemoActivity.MSG_UNREGISTER_CLIENT:
                    // 注销客户端
                    if (msg.replyTo != null) {
                        clients.remove(msg.replyTo);
                        Log.d(TAG, "客户端已注销，当前客户端数量: " + clients.size());
                    }
                    break;
                case MessengerDemoActivity.MSG_SET_VALUE:
                    // 接收客户端发送的消息
                    Bundle data = msg.getData();
                    if (data != null) {
                        String receivedValue = data.getString("data");
                        if (receivedValue != null) {
                            // 处理消息（这里简单地加上时间戳后回复）
                            currentValue = receivedValue + " [服务端已处理: " + System.currentTimeMillis() % 10000 + "]";
                            Log.d(TAG, "收到消息: " + receivedValue + "，已更新为: " + currentValue);
                            
                            // 回复给发送消息的客户端
                            if (msg.replyTo != null) {
                                replyToClient(msg.replyTo, currentValue);
                            }
                            
                            // 通知所有其他客户端数据变化
                            notifyValueChangedToAllClients(msg.replyTo);
                        }
                    }
                    break;
                case MessengerDemoActivity.MSG_GET_VALUE:
                    // 处理客户端的数据请求
                    if (msg.replyTo != null) {
                        replyToClient(msg.replyTo, currentValue);
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    // 创建服务端Messenger
    private final Messenger messenger = new Messenger(new IncomingHandler());

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "MessengerService onBind，进程ID: " + Process.myPid());
        return messenger.getBinder();
    }

    // 向单个客户端回复消息
    private void replyToClient(Messenger client, String value) {
        try {
            Message message = Message.obtain(null, MessengerDemoActivity.MSG_VALUE_CHANGED);
            Bundle bundle = new Bundle();
            bundle.putString("data", value);
            message.setData(bundle);
            client.send(message);
            Log.d(TAG, "已回复客户端: " + value);
        } catch (RemoteException e) {
            // 客户端可能已死亡
            Log.e(TAG, "回复客户端失败: " + e.getMessage());
            clients.remove(client);
        }
    }

    // 通知所有客户端数据变化（除了消息发送者）
    private void notifyValueChangedToAllClients(Messenger sender) {
        for (int i = clients.size() - 1; i >= 0; i--) {
            Messenger client = clients.get(i);
            // 跳过消息发送者，避免重复通知
            if (client.equals(sender)) {
                continue;
            }
            
            try {
                Message message = Message.obtain(null, MessengerDemoActivity.MSG_VALUE_CHANGED);
                Bundle bundle = new Bundle();
                bundle.putString("data", currentValue + " [广播通知]");
                message.setData(bundle);
                client.send(message);
                Log.d(TAG, "已通知客户端 #" + i);
            } catch (RemoteException e) {
                // 客户端可能已死亡，从列表中移除
                Log.e(TAG, "通知客户端 #" + i + " 失败: " + e.getMessage());
                clients.remove(i);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "MessengerService onCreate，进程ID: " + Process.myPid());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "MessengerService onDestroy");
        clients.clear();
    }
} 